#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <UIKit/UIKit.h>
#import <UIKit/UIApplication.h>
#import <Preferences/PSSpecifier.h>

#import "framework/FWApplication.h"
#import "framework/FWCommon.h"

#import "PIIntegration.h"
#import "PICommon.h"

#import "PIAboutPrefs.h"

#define STR_EXPAND(tok) #tok
#define STR(tok) STR_EXPAND(tok)


static NSString* const kProductVersion = @STR(APP_VERSION);


@implementation PIAboutPrefs


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

- (id)initForContentSize:(CGSize)contentSize
{
    if ([super respondsToSelector:@selector(initForContentSize:)])
        self = [super initForContentSize:contentSize];
    else
        self = [super init];
    
    if (self) {
        titleLocalised = NO;
    }
    
    return self;
}

- (void)dealloc
{
    [_specifiers release];
    _specifiers = nil;
    
    [super dealloc];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Get about page

- (NSArray *)specifiers
{
    if (!_specifiers) {
        NSString* key = [[self specifier] propertyForKey:@"key"];
        DebugLog(@"LI:PICommon: Loading specifiers from %@", key);

        NSArray* specs = [self loadSpecifiersFromPlistName:key target:self];
        specs = [self localizedSpecifiersForSpecifiers:specs];

        titleLocalised = NO;
        _specifiers = [specs retain];
    }
    
    return _specifiers;
}

- (NSArray*)localizedSpecifiersForSpecifiers:(NSArray*)specs
{
    DebugLog(@"LI:PICommon: Specifiers %@", specs);
    NSBundle* bundle = [NSBundle bundleForClass:[self class]];
    
    NSMutableArray* newSpecs = [NSMutableArray arrayWithCapacity:specs.count];

    for (PSSpecifier* spec in specs) {

#ifndef DEBUG
        if (NSObject* debug = [spec propertyForKey:@"debug"]) {
            XLog(@"LI:PICommon: debug item; name = %@", spec.name);
            continue;
        }
#endif
        
        if (NSString* footer = [spec propertyForKey:@"footerText"]) {
            NSString* msg = localize(bundle, footer);
            msg = [msg stringByReplacingOccurrencesOfString:@"$VERSION$" withString:kProductVersion];
            [spec setProperty:msg forKey:@"footerText"];
        }

        if (NSString* url = [spec propertyForKey:@"URL"]) {
            NSString* msg = [url stringByReplacingOccurrencesOfString:@"$VERSION$" withString:kProductVersion];
            [spec setProperty:msg forKey:@"URL"];
        }

        if (NSString* name = [spec name]) {
            NSString* newName = localize(bundle, name);
            if ([newName rangeOfString:@"$APPLICATION$"].location != NSNotFound) {
                UIPasteboard* pasteBoard = [UIPasteboard pasteboardWithName:kPIStatusPasteboard create:NO];
                if (NSString* appType = FWStringValueFromPasteboard(pasteBoard, kPIPasteboardAppType)) {
                    if ([appType isEqualToString:PIProIdentifier])
                        appType = localize(bundle, @"Debug/Datasource/Pro");
                    else if ([appType isEqualToString:PIiPhoneIdentifier])
                        appType = localize(bundle, @"Debug/Datasource/iPhone");
                    else if ([appType isEqualToString:PILiteIdentifier])
                        appType = localize(bundle, @"Debug/Datasource/Lite");
                    else
                        appType = localize(bundle, @"Debug/Datasource/None");
                    newName = [newName stringByReplacingOccurrencesOfString:@"$APPLICATION$" withString:appType];
                }
            }
            [spec setName:newName];
        }

        if ([spec titleDictionary]) {
            NSMutableDictionary* newTitles = [NSMutableDictionary dictionaryWithDictionary:[spec titleDictionary]];
            NSArray* keys = [newTitles allKeys];
            for (NSString* key in keys) {
                [newTitles setObject:localize(bundle, [newTitles objectForKey:key]) forKey:key];
            }
            [spec setTitleDictionary:newTitles];
        }
        
        [newSpecs addObject:spec];

        DebugLog(@"LI:PICommon: Localized %@ titles %@", [spec name], [spec titleDictionary]);
    }
    
    DebugLog(@"LI:PICommon: Localized Specifiers %@", specs);

    return newSpecs;
}

- (void)viewWillAppear:(BOOL)arg1
{
//    NSLog(@"XXXXXXXXX: viewWillAppear %d", arg1);
//    
//    if (_specifiers) {
//        for (PSSpecifier* spec in _specifiers) {
//            NSLog(@"XXXXXXXX: spec %@", [spec properties]);
////            NSString* x = [spec propertyForKey:@"detail"];
////            if ([x isEqualToString:@"PIEventCalendarPrefs"]) {
////                NSObject* y = [spec propertyForKey:@"cellObject"];
////                [y performSelector:@selector(setValue:) withObject:@"hello"];
////            }
//        }
//    }
    
    if ([super respondsToSelector:@selector(viewWillAppear:)])
        [super viewWillAppear:arg1];
}

- (void)viewWillDisappear:(BOOL)arg1
{
    NSLog(@"XXXXXXXXX: viewWillDisappear %d", arg1);
    
    if ([super respondsToSelector:@selector(viewWillDisappear:)])
        [super viewWillDisappear:arg1];
}

//-(void)viewDidLoad
//{
//    NSLog(@"Loading Application");
//    [super viewDidLoad];
//}
//
//- (void)viewWillBecomeVisible:(void *)source
//{
//    NSLog(@"View Becoming Visible", source);
//    [super viewWillBecomeVisible:source];
//}

- (id)navigationItem
{
    UINavigationItem* item = [super navigationItem];

    if (!titleLocalised) {
        NSBundle* bundle = [NSBundle bundleForClass:[self class]];
        [item setTitle:localize(bundle, item.title)];
        
        titleLocalised = YES;
    }
    
    return item;
}

@end
